package br.com.utfpr.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.utfpr.consumer.Consultas;

public class PrincipalServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = null;
		Consultas consulta = null;
		String acao = request.getParameter("acao");
		
		if (acao == null || "".equals(acao)) {
			dispatcher = getServletContext().getRequestDispatcher("/pages/index.jsp");
		} else if ("2".equals(acao)) {
			if(request.getParameter("subAcao") != null) {
				consulta = new Consultas();
				int quantidade = consulta.consultarQunatidadeCidades(request.getParameter("estado"));
				
				request.setAttribute("quantidade", new Integer(quantidade).toString()); 
				request.setAttribute("estado", request.getParameter("estado")); 
			}
			
			dispatcher = getServletContext().getRequestDispatcher("/pages/quantidadeMunicipios.jsp");
		} else if ("3".equals(acao)) {
			if(request.getParameter("subAcao") != null) {
				consulta = new Consultas();
				String nome = consulta.consultarNomeCidade(new Integer(request.getParameter("codIBGE")).intValue());
				
				request.setAttribute("nomeCidade", nome); 
				request.setAttribute("codIBGE", request.getParameter("codIBGE")); 
			}
			
			dispatcher = getServletContext().getRequestDispatcher("/pages/nomeMunicipio.jsp");
		} else if ("4".equals(acao)) {
			if(request.getParameter("subAcao") != null) {
				consulta = new Consultas();
				int codigo = consulta.consultarCodigoIbgeMunicipio(request.getParameter("municipio"), request.getParameter("estado"));
				
				request.setAttribute("codigoIBGE", new Integer(codigo).toString()); 
				request.setAttribute("municipio", request.getParameter("municipio").toUpperCase());
				request.setAttribute("estado", request.getParameter("estado").toUpperCase()); 
			}
			
			dispatcher = getServletContext().getRequestDispatcher("/pages/codigoIbge.jsp");
		}
		
        dispatcher.forward(request, response);
	}
	
//	@Override
//	protected void doGet(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		System.out.println("GGGGGGGGGGGGGGGGGGGGG");
//		System.out.println("ACAO: " + request.getParameter("acao"));
//        getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
//		response.sendRedirect("/pages/index.jsp");
//	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPP");
		System.out.println("ACAO: " + request.getParameter("acao"));
	}

}
